package hluck.me.srorage.sys.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import hluck.me.srorage.sys.common.ActiveUser;
import hluck.me.srorage.sys.common.Constast;
import hluck.me.srorage.sys.domain.SysPermission;
import hluck.me.srorage.sys.domain.SysUser;
import hluck.me.srorage.sys.service.SysPermissionService;
import hluck.me.srorage.sys.service.SysRoleService;
import hluck.me.srorage.sys.service.SysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    @Lazy
    private SysUserService userService;
    @Autowired
    @Lazy
    private SysPermissionService permissionService;
    @Autowired
    @Lazy
    private SysRoleService roleService;

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        QueryWrapper<SysUser> wrapper=new QueryWrapper<>();
        wrapper.eq("loginname",token.getPrincipal().toString());
        SysUser sysUser = userService.getOne(wrapper);

        if (sysUser!=null) {
            ActiveUser activeUser = new ActiveUser();
            activeUser.setUser(sysUser);
            //根据用户ID查询percode
            //查询所有权限
            QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
            //只查询权限
            queryWrapper.eq("type", Constast.TYPE_PERMISSION);
            queryWrapper.eq("available",Constast.AVAILABLE_TRUE);
            Integer userId = sysUser.getId();
            //根据用户ID查询角色
            List<Integer> rids = roleService.queryUserRoleIdsByUid(userId);
            //根据角色ID取到权限和菜单 ID
            HashSet<Integer> pids = new HashSet<>();
            for (Integer rid : rids) {
                List<Integer> permissionIds = roleService.queryRolePermissionIdsByRid(rid);
                pids.addAll(permissionIds);
            }
            List<SysPermission> list=new ArrayList<>();;
            //根据权限id查询对应权限
            if (pids.size()>0) {
                queryWrapper.in("id",pids);
                list=permissionService.list(queryWrapper);
            }
            List<String> percodes=new ArrayList<>();
            for (SysPermission permission : list) {
                percodes.add(permission.getPercode());
            }
            activeUser.setPermissions(percodes);


            ByteSource credentialsSalt = ByteSource.Util.bytes(sysUser.getSalt());
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activeUser, sysUser.getPwd(), credentialsSalt, this.getName());
            return info;
        }
        return null;
    }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        ActiveUser activeUser= (ActiveUser) principals.getPrimaryPrincipal();
        SysUser user=activeUser.getUser();
        List<String> permissions = activeUser.getPermissions();
        //超级管理员拥有所有权限
        if (user.getType()== Constast.USER_TYPE_SUPPER) {
            authorizationInfo.addStringPermission("*:*");
        }else {
            if (null!=permissions&&permissions.size()>0){
                authorizationInfo.addStringPermissions(permissions);
            }
        }
        return authorizationInfo;
    }
}
